#!/usr/bin/env python
# Chen Wen <chenpc@cs.nctu.edu.tw>
# Web Site http://code.google.com/p/comicdl/
# Blog : http://chenpc.csie.in
from subprocess import call
import httplib, urllib2, string,sys, os, re
from multiprocessing import Pool, Lock
pagecount=0

def savefile(url, folder, filename):
	call("curl -C - -s %s -o %s/%s.jpg" % (url, folder, filename), shell=True)
	print folder, filename
		

dlurl = sys.argv[1]

m = re.match(r"http://www.8comic.com/html/(.*).html", dlurl)

if m != None:
	dlurl = "http://www.8comic.com/love/drawing-%s.html" % (m.group(1))

m = re.match(r"http://www.8comic.com/love/drawing-(.*).html", dlurl)

if m == None:
	print "Invalid URL."
	sys.exit(1)

url = urllib2.urlopen(dlurl, timeout=30)

html = url.read()

i1 = string.index(html, 'var codes="')
i2 = string.index(html, '.split(\'|\');')

section = html[i1+11:i2-1].split("|")
tmp1 = string.index(html, 'var itemid=')
tmp2 = string.index(html, 'if(ch=="")')
itemid = html[tmp1+11:tmp2-3]
proccess = 0

skip = 0
if len(sys.argv) > 2:
	skip = int(sys.argv[2])

for ch in section:
	if ch < skip:
		continue
	tok = ch.split(" ")

	num = tok[0]
	sid = tok[1]
	did = tok[2]
	page = tok[3]
	code = tok[4]
	pages = int(page)
	pagecount = 0
	
	if skip > int(num):
		continue
	if os.access("%s.zip" % (num), os.F_OK):
		call("rm -rf %s" % (num), shell=True)
		continue
	if not os.access(num, os.F_OK):
		os.mkdir(num)

	for p in xrange(1, pages+1):
		if p<10:
			img="00"+str(p)
		elif p<100:
			img="0"+str(p)
		else:
			img=str(p)

		m = ((p-1)/10)%10 + (((p-1)%10)*3)
		pimg=img+"_"+code[m:m+3]

		imgurl = "http://img%s.8comic.com/%s/%s/%s/%s.jpg" % (sid, did, itemid, num, pimg)
		savefile(imgurl, num, img)
	call("zip -qr %s.zip %s" % (num, num), shell=True)
	call("rm -rf %s" % (num), shell=True)
